package com.wfu.module_local_video;


import android.annotation.SuppressLint;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.wfu.module_base.base.BaseFragment;
import com.wfu.module_base.utils.RouteUtils;
import com.wfu.module_base.utils.ToastUtils;
import com.wfu.module_local_video.adapter.LocalVideoAdapter;
import com.wfu.module_local_video.bean.MediaItem;
import com.wfu.module_local_video.business.LVideoBusiness;
import com.wfu.module_local_video.view.LVideoView;

import java.util.List;


@Route(path = RouteUtils.LOCAL_VIDEO_FRAGMENT)
public class LVideoFragment extends BaseFragment implements LVideoView<List<MediaItem>> {
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LocalVideoAdapter mAdapter;

    private View noDataView;
    private View errorView;
    private LVideoBusiness mPresenter;

    @Override
    protected int bindLayout() {
        return R.layout.fragment_local_video;
    }

    @Override
    protected void initResource() {
        mPresenter = new LVideoBusiness(this);
    }

    @Override
    protected void initWidget() {
        mRefreshLayout = getView(R.id.swp_local_video);
        mRecyclerView = getView(R.id.rv_local_video);
        noDataView = inflate(R.layout.empty_view);
        errorView = inflate(R.layout.error_view);

        initEvent();
        initRecyclerView();
        initData();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        mAdapter = new LocalVideoAdapter(R.layout.item_local_video, null);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ToastUtils.showLongToast(mAdapter.getData().get(position).artist);
        });

    }

    private void initEvent() {
        noDataView.setOnClickListener(v -> initData());
        errorView.setOnClickListener(v -> initData());
        mRefreshLayout.setOnRefreshListener(() -> initData());
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initData() {
        mPresenter.getLocalVideoFromSD(mContext);
    }

    @Override
    public void setLoadingVisiblity(boolean visiblity) {
        mRefreshLayout.setRefreshing(visiblity);
    }

    @Override
    public void onSuccess(List<MediaItem> data) {
        if (data.size() > 0) {
            mAdapter.setNewData(data);
        } else {
            mAdapter.setEmptyView(noDataView);
        }
    }

    @Override
    public void onFailed(Throwable throwable) {
        mAdapter.setEmptyView(errorView);
    }
}
